package com.maddox.relax.helper;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

import com.maddox.relax.model.ImageInfo;
import com.maddox.relax.model.ImageSet;
import com.maddox.relax.model.MimeType;
import com.maddox.relax.util.AppUtils;
import com.maddox.relax.util.LogUtil;
import com.maddox.relax.util.PBitmapUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Set;

import static com.maddox.relax.model.MediaStoreConstants.*;

/**
 * 选择相册中的文件或者内容
 */
public class MediaStorageSource implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int LOADER_ID = 99;

    private WeakReference<FragmentActivity> mContext;

    private LoaderManager loaderManager;

    private ImageSet imageSet = new ImageSet();

    private Set<MimeType> mimeTypeSet;

    private Cursor cursor;

    private Thread thread;


    public MediaItemPreLoadProvider preLoadProvider;


    private MediaStorageSource(FragmentActivity activity) {
        this.mContext = new WeakReference<>(activity);
        loaderManager = LoaderManager.getInstance(mContext.get());

    }

    private MediaStorageSource() {
    }

    //创建相册操作实例
    public static MediaStorageSource create(FragmentActivity activity) {
        return new MediaStorageSource(activity);
    }

    //设置选择的相册文件类型
    public MediaStorageSource setMediaType(int type) {
        switch (type) {
            case -10:
                imageSet.id = ImageSet.TYPE_ALL_MEDIA;
                break;
            case -100:
                imageSet.id = ImageSet.TYPE_ALL_IMAGE;
                break;
            case -200:
                imageSet.id = ImageSet.TYPE_ALL_VIDEO;
                break;
        }
        return this;

    }

    //设置要筛选的文件类型具体
    public MediaStorageSource setMimeTypeSet(Set<MimeType> mimeTypeSet) {
        if (mimeTypeSet == null) {
            mimeTypeSet = MimeType.ofAll();
        }
        this.mimeTypeSet = mimeTypeSet;
        return this;
    }

    public void loadMediaDatas(MediaItemPreLoadProvider provider) {
        this.preLoadProvider = provider;
        loaderManager.initLoader(LOADER_ID, null, this);
    }



    @NonNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
        Context context = mContext.get();
        if (context == null) return null;
        if (mimeTypeSet == null || mimeTypeSet.size() == 0) {
            mimeTypeSet = MimeType.ofAll();
        }

        return MediaInfoLoader.newInstance(context, imageSet, mimeTypeSet);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
        FragmentActivity activity = mContext.get();
        if (activity == null || data == null || data.isClosed()) {
            LogUtil.d("查询媒体类型数据为空!");
            return;
        }
        this.cursor = data;
        if (thread != null && thread.isAlive()) {
            return;
        }
        thread = new Thread(runnable);
        thread.start();

    }

    private Runnable runnable = () -> {
        FragmentActivity context = mContext.get();
        ArrayList<ImageInfo> imageInfos = new ArrayList<>();
        if (!context.isDestroyed() && !cursor.isClosed() && cursor.moveToFirst()) {
            do {
                ImageInfo imageInfo = new ImageInfo();
                try {
                    imageInfo.id = getLong(cursor, _ID);
                    imageInfo.mimeType = getString(cursor, MIME_TYPE);
                    imageInfo.displayName = getString(cursor, DISPLAY_NAME);
                    //获取绝对路径,取不到再去拼接uri
                    try {
                        imageInfo.filePath = getString(cursor, DATA);
                    } catch (Exception e) {

                    }
                    Uri uriPath = imageInfo.getUri();
                    if (uriPath != null) {
                        imageInfo.setUriPath(uriPath.toString());
                    }

                    if (imageInfo.filePath == null || imageInfo.filePath.length() == 0) {
                        imageInfo.filePath = uriPath.toString();
                    }

                    imageInfo.width = getInt(cursor, WIDTH);
                    imageInfo.height = getInt(cursor, HEIGHT);
                    imageInfo.setVideo(MimeType.isVideo(imageInfo.getMimeType()));
                    imageInfo.time = getLong(cursor, DATE_MODIFIED);
                    imageInfo.timeFormat = AppUtils.getStrTime(imageInfo.time);
                } catch (Exception e) {
                    continue;
                }

                if (imageInfo.filePath == null || imageInfo.filePath.length() == 0) {
                    continue;
                }
                if (imageInfo.isVideo()) {
                    imageInfo.duration = getLong(cursor, DURATION);
                    if (imageInfo.duration == 0) {
                        continue;
                    }
                    imageInfo.durationFormat = AppUtils.getVideoDuration(imageInfo.duration);

                } else {
                    if (imageInfo.width == 0 || imageInfo.height == 0) {
                        if (imageInfo.isUriPath()) {
                            int[] size = PBitmapUtils.getImageWidthHeight(imageInfo.filePath);
                            imageInfo.width = size[0];
                            imageInfo.height = size[1];
                        }
                    }

                }
                imageInfos.add(imageInfo);
            } while (cursor.moveToNext());
            LogUtil.d("解析所有完成-->" + imageInfos);
            notifyMediaItem(context, imageInfos);

        }

    };

    private void notifyMediaItem(FragmentActivity context, ArrayList<ImageInfo> imageInfos) {
        if (context == null || context.isDestroyed()) {
            return;
        }
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
             preLoadProvider.providerMediaItems(imageInfos,imageSet.id);
            }
        });


    }

    private long getLong(Cursor cursor, String column) {
        int index = hasColumn(cursor, column);
        if (index != -1) {
            return cursor.getLong(index);
        }
        return 0;
    }

    private int getInt(Cursor cursor, String column) {
        int index = hasColumn(cursor, column);
        if (index != -1) {
            return cursor.getInt(index);
        }
        return 0;
    }

    private String getString(Cursor cursor, String column) {
        int index = hasColumn(cursor, column);
        if (index != -1) {
            return cursor.getString(index);
        }
        return "";
    }

    private int hasColumn(Cursor data, String id) {
        try {
            return data.getColumnIndexOrThrow(id);
        } catch (IllegalArgumentException e) {
            LogUtil.d("获取字段-->" + id + "---的角标出错:" + e.getMessage());
            return -1;
        }
    }

    @Override
    public void onLoaderReset(@NonNull Loader<Cursor> loader) {

    }

    public interface MediaItemPreLoadProvider {

        void providerMediaItems(ArrayList<ImageInfo> imageInfos,int mediaType);
    }

}
